var role = $.cookie("role");
var path = 'localhost:8080/';
var fromName = $.cookie("studentName");
var from = $.cookie("student");
var to= "群聊";
var toicon = null;
var list = null;
var myAvatar = $.cookie("studenticon"); // 存储自己的头像
const chatMessages = document.getElementById('chat-messages');
const emojiBtn = document.getElementById('emoji-btn');
const emojiPicker = document.getElementById('emoji-picker');
const closeEmoji = document.querySelector('.close-emoji');
const emojiGrid = document.querySelector('.emoji-grid');
const messageInput = document.getElementById('message-input');
var current = null;
// 获取元素
const imageBtn = document.getElementById('image-btn');
const fileBtn = document.getElementById('file-btn');
const fileInput = document.getElementById('fileInput');
const imageInput = document.getElementById('imageInput');
const sendBtn = document.getElementById('send-btn');
const chatList = document.querySelector(".chat-list")
console.log(fromName, from)
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

var websocket;
if ('WebSocket' in window) {
    websocket = new WebSocket("ws://" + path + "ws");
}

// 存储在线用户列表
var onlineUsers = [];

websocket.onopen = function(event) {
    console.log("WebSocket:已连接");
    // 发送自己的信息给服务器
    // var data = {
    //     type: "login",
    //     id: from,
    //     name: fromName,
    //     avatar: myAvatar,
    //     role: role
    // };
    // websocket.send(JSON.stringify(data));
    var avaterimg = "https://lyf-java-ai.oss-cn-beijing.aliyuncs.com/2025/07/135a9a6b-e900-4e76-8108-b90bb04b1cde.jpg";
    $(".chat-header .header-left .avatar img").attr("src",avaterimg)
    console.log(avaterimg)
};

websocket.onmessage = function(event) {
    var data = $.parseJSON(event.data);
    console.log("WebSocket:收到一条消息", data);

    if (data.type === "userList") {
        // 更新在线用户列表

    } else if (data.type === "message") {
        console.log(data)
        console.log("自己是"+fromName);
        console.log("发消息的是"+data.fromName);
        console.log("当前页面是"+to);
        console.log("要发送给的人是"+data.to);

// 应该显示消息的三种情况：
// 1. 消息是我自己发送的（无论发给谁）
// 2. 消息是发给当前聊天对象（to）的
// 3. 当前在群聊中且这是群消息

        if(fromName === data.fromName) {
            // 情况1：我自己发送的消息（显示所有自己发的消息）
            addMessageToChat(data);
        }else if(data.to=="群聊" && to == "群聊"){
            addMessageToChat(data)
        }else if(data.to == fromName && to == data.fromName){
            addMessageToChat(data)
        }
    } else if (data.type === "system") {
        // 处理系统消息
        addSystemMessage(data.text);
        updateOnlineUsers(data.userList);
        $(".chat-title h3").html(to)
        list = data.userList
        $(".chat-title p").html(data.userList.length + "位在线")
        if(data.data != null){
            updateChatMessages(data, fromName)
        }
        // 初始化滚动到底部
    }else if(data.type=="ChangeSingle"){
        console.log(data)
        // const chatMessagesContainer = document.getElementById('chat-messages');
        // chatMessagesContainer.innerHTML = renderChatMessages(data.data,fromName);

        // chatMessagesContainer.scrollTop = chatMessages.scrollHeight;
        updateChatMessages(data, fromName)
    }
};

async function updateChatMessages(data, fromName) {
    const chatMessagesContainer = document.getElementById('chat-messages');

    // 1. 保存当前滚动状态
    const wasScrolledToBottom =
        chatMessagesContainer.scrollTop + chatMessagesContainer.clientHeight >=
        chatMessagesContainer.scrollHeight - 10;

    // 2. 渲染内容
    chatMessagesContainer.innerHTML = renderChatMessages(data.data, fromName);

    // 3. 确保滚动到底部
    await new Promise(resolve => requestAnimationFrame(resolve));
    if (wasScrolledToBottom) {
        chatMessagesContainer.scrollTop = chatMessagesContainer.scrollHeight;
    }
}

// websocket.onclose = function(event) {
//     console.log("WebSocket连接已关闭");
//     addSystemMessage("连接已断开，请刷新页面重新连接");
// };
websocket.onerror = function(event) {
    console.error("WebSocket错误:", event);
    addSystemMessage("连接发生错误");
};
// 更新在线用户列表
function updateOnlineUsers(users) {
    console.log(users)
    onlineUsers = users.filter(user => {
        // 如果 sno 不为 null，并且 user.id 不等于 from
        return user.name !== fromName;
    }); // 过滤掉自己
    console.log(onlineUsers)
    const onlineUsersList = document.getElementById('online-users');
    onlineUsersList.innerHTML = `
<div class="chat-item active-dom">
          <div class="avatar">
                <img src="https://lyf-java-ai.oss-cn-beijing.aliyuncs.com/2025/07/135a9a6b-e900-4e76-8108-b90bb04b1cde.jpg" alt="群聊">
            </div>
            <div class="chat-info">
                <h3>群聊</h3>
                <p>群聊</p>
          </div>
</div>
`;
    onlineUsers.forEach(user => {
        if (!user || Object.keys(user).length === 0) {
            return; // 相当于continue
        }
        const userItem = document.createElement('div');
        userItem.className = 'chat-item';
        userItem.innerHTML = `
            <div class="avatar">
                <img src="${user.icon || 'https://via.placeholder.com/40'}" alt="${user.name}">
            </div>
            <div class="chat-info">
                <h3>${user.name}</h3>
                <p>${user.workNumber == null ? '学生' : '老师'}</p>
            </div>
        `;
        onlineUsersList.appendChild(userItem);
    });
    onlineUsersList.innerHTML += `
<div class="chat-item">
          <div class="avatar">
                <img src="https://lyf-java-ai.oss-cn-beijing.aliyuncs.com/2025/07/ee27f9db-f62f-4c79-9f54-9f43003ec7bd.webp" alt="Ai聊天">
            </div>
            <div class="chat-info">
                <h3>AI</h3>
                <p>AI</p>
          </div>
</div>
`;
}
// 添加系统消息
function addSystemMessage(text) {
    const chatMessages = document.getElementById('chat-messages');
    const messageElement = document.createElement('div');
    messageElement.className = 'message-date';
    messageElement.textContent = text;
    chatMessages.appendChild(messageElement);
    chatMessages.scrollTop = chatMessages.scrollHeight;

}

// 添加普通消息
function addMessageToChat(data) {

    const chatMessages = document.getElementById('chat-messages');
    const isMe = data.fromName === fromName;

    setLoading(data.btnShow)
    const currentTime = formatTime(data.timestamp || new Date().getTime());
    const messageClass = isMe ? 'sent' : 'received';
    console.log(data.text+"普通信息")
    if (isMe) {
        chatMessages.innerHTML+=`
            <div class="message ${messageClass}">
                <div class="avatar">
                    <img src="${data.fromicon || 'https://via.placeholder.com/32'}" alt="${data.fromName}">
                </div>
                <div class="message-content">
                    <div class="message-info">
                        ${!isMe ? `<span class="sender">${data.fromName}</span>` : ''}
                        <span class="time">${currentTime}</span>
                    </div>
                    ${renderMessageContent(data)}
                    ${isMe ? `
                    <div class="message-status">
                        <i class="fas fa-check-double"></i>
                    </div>` : ''}
                </div>
            </div>
        `;
    } else {
        const sender = onlineUsers.find(user => user.name == data.fromName) || {};
        chatMessages.innerHTML+=`
            <div class="message ${messageClass}">
                <div class="avatar">
                    <img src="${data.fromicon || 'https://via.placeholder.com/32'}" alt="${data.fromName}">
                </div>
                <div class="message-content">
                    <div class="message-info">
                        ${!isMe ? `<span class="sender">${data.fromName}</span>` : ''}
                        <span class="time">${currentTime}</span>
                    </div>
                    ${renderMessageContent(data)}
                    ${isMe ? `
                    <div class="message-status">
                        <i class="fas fa-check-double"></i>
                    </div>` : ''}
                </div>
            </div>
        `;
    }
    chatMessages.scrollTop = chatMessages.scrollHeight;

}

// 发送消息
function sendMessage() {
    console.log("发送消息")
    let messageText = messageInput.value.trim();
    console.log(websocket)
    let data;
    if (messageText && websocket) {
        console.log(1)
        data = {
            type: "message",
            text: messageText,
            fromName: fromName,
            // time: new Date().getTime()
            fromicon: myAvatar,
            to:to,
            toicon: toicon
        };
        websocket.send(JSON.stringify(data));
        messageInput.value = '';

    }
}

// 格式化时间
function formatTime(timestamp) {
    const date = new Date(timestamp);
    return date.getHours().toString().padStart(2, '0') + ':' +
        date.getMinutes().toString().padStart(2, '0');
}

// 滚动到底部
function scrollToBottom() {
    const chatMessages = document.getElementById('chat-messages');
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化滚动到底部
    const chatMessages = document.getElementById('chat-messages');
    chatMessages.scrollTop = chatMessages.scrollHeight;
});
function renderMessageContent(message) {
    // 检查是否是图片（简单判断，实际应根据文件类型或URL扩展名）
    const isImage = message.text.match(/\.(jpeg|jpg|gif|png|webp)$/i) ||
        (message.fileType && message.fileType.startsWith('image/'));

    // 检查是否是文件
    const isFile = message.fileType && !isImage;

    const hasNonEmoji = /[^\p{Emoji}]/u.test(message.text);

    const emojiClass = !hasNonEmoji ? 'has-emoji' : '';
    // 决定是否添加emoji相关类

    if (isImage) {
        // 图片消息
        return `
            <div class="message-media">
                <img src="${message.text}" alt="图片" class="message-image" onclick="previewImage('${message.text}')">
                ${message.caption ? `<div class="image-caption">${message.caption}</div>` : ''}
            </div>
        `;
    } else if (isFile) {
        // 文件消息
        return `
<div class="message-file">
    <div class="file-info">
        <i class="fas ${getFileIcon(message.fileType)} file-icon"></i>
        <div>
            <div class="file-name">${message.fileName || '下载文件'}</div>
            <div class="file-size">${formatFileSize(message.fileSize)}</div>
        </div>
    </div>
    <a href="${message.text}" class="download-btn" download>下载</a>
</div>
        `;
    } else if (emojiClass) {
        // Emoji消息（大表情）
        return `
            <div class="message-emoji">
                ${message.text}
            </div>
        `;
    } else {
        // 普通文本消息（支持换行和基本HTML转义）
        const safeText = message.text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/\n/g, "<br>");

        return `
            <div class="message-text">
                ${safeText}
            </div>
        `;
    }
}

// 辅助函数：获取文件类型图标
function getFileIcon(fileType) {
    if (!fileType) return 'fa-file';

    const typeMap = {
        'application/pdf': 'fa-file-pdf',
        'application/msword': 'fa-file-word',
        'application/vnd.ms-excel': 'fa-file-excel',
        'application/vnd.ms-powerpoint': 'fa-file-powerpoint',
        'application/zip': 'fa-file-archive',
        'text/plain': 'fa-file-alt'
    };

    return typeMap[fileType] || 'fa-file';
}

// 辅助函数：格式化文件大小
function formatFileSize(bytes) {
    if (!bytes) return '';
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
    return (bytes / 1048576).toFixed(1) + ' MB';
}

// 图片预览函数
function previewImage(src) {
    // 实现图片预览逻辑，可以使用Lightbox等库
    console.log('预览图片:', src);
}

// 修改后的renderChatMessages函数
function renderChatMessages(messages, currentUser) {
    let html = '';

    if (!messages || messages.length === 0) {
        return '<div class="message-date">暂无消息</div>';
    }

    html += '<div class="message-date">今天</div>';

    messages.forEach(message => {
        const isCurrentUser = message.fromName === currentUser;
        const messageClass = isCurrentUser ? 'sent' : 'received';
        const currentTime = formatTime(message.timestamp || new Date().getTime());
        html += `
            <div class="message ${messageClass}">
                <div class="avatar">
                    <img src="${message.fromicon || 'https://via.placeholder.com/32'}" alt="${message.fromName}">
                </div>
                <div class="message-content">
                    <div class="message-info">
                        ${!isCurrentUser ? `<span class="sender">${message.fromName}</span>` : ''}
                        <span class="time">${currentTime}</span>
                    </div>
                    ${renderMessageContent(message)}
                    ${isCurrentUser ? `
                    <div class="message-status">
                        <i class="fas fa-check-double"></i>
                    </div>` : ''}
                </div>
            </div>
        `;
    });
    const chatMessages = document.getElementById('chat-messages');
    chatMessages.scrollTop = chatMessages.scrollHeight;
    return html;
}

// Emoji 选择器功能
emojiBtn.addEventListener('click', function() {
    console.log(1)
    emojiPicker.classList.toggle('show');
});

closeEmoji.addEventListener('click', function() {
    emojiPicker.classList.remove('show');
});

emojiGrid.addEventListener('click', function(e) {
    if (e.target.tagName === 'BUTTON') {
        messageInput.value += e.target.textContent;
        messageInput.focus();
    }
});



// 图片按钮点击事件 - 触发图片选择
imageBtn.addEventListener('click', () => {
    imageInput.click(); // 触发隐藏的imageInput点击
});

// 文件按钮点击事件 - 触发文件选择
fileBtn.addEventListener('click', () => {
    fileInput.click(); // 触发隐藏的fileInput点击
});

// 图片选择处理
imageInput.addEventListener('change', function() {
    if (this.files && this.files[0]) {
        const file = this.files[0];
        const formData = new FormData();
        formData.append("file", file);  // "file" 必须和后端参数名一致
        $.ajax({
            url: "/upload",  // 替换为你的Servlet URL
            type: "POST",
            data: formData,
            processData: false,      // 禁止jQuery处理数据（文件上传必须）
            contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
            cache: false,            // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
            success: function (response) {
                if (file.type.startsWith('image/')) {
                    sendImageMessage(response.data);
                } else {
                    alert('请选择图片文件');
                }
            },error: function(xhr, status, error) {
                console.error("上传失败:", error);
                $("#result").html("上传失败: " + (xhr.responseText || error));
            }

        });
        this.value = ''; // 重置input
    }
});

// 文件选择处理
fileInput.addEventListener('change', function() {
    if (this.files && this.files[0]) {
        const file = this.files[0];
        console.log(file)
        const formData = new FormData();
        formData.append("file", file);  // "file" 必须和后端参数名一致
        $.ajax({
            url: "/upload",  // 替换为你的Servlet URL
            type: "POST",
            data: formData,
            processData: false,      // 禁止jQuery处理数据（文件上传必须）
            contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
            cache: false,            // 禁用缓存// 禁止设置Content-Type请求头（浏览器会自动设置）
            success: function (response) {

                sendFileMessage(response.data,file);
            },error: function(xhr, status, error) {
                console.error("上传失败:", error);
                $("#result").html("上传失败: " + (xhr.responseText || error));
            }

        });
        this.value = ''; // 重置input
    }
});
// 发送图片消息函数 - 修改为无气泡样式，头像在右侧
function sendImageMessage(file) {
    const data = {
        type: "message",
        text: file,
        fromName: fromName,
        // time: new Date().getTime()
        fromicon: myAvatar,
        to:to,
        toicon:toicon
    };
    websocket.send(JSON.stringify(data));
}

// 发送文件消息函数 - 修改为无气泡样式，头像在右侧
function sendFileMessage(file,fileTrue) {
    const messageElement = document.createElement('div');
    const data = {
        type: "message",
        text: file,
        fromName: fromName,
        // time: new Date().getTime()
        fromicon: myAvatar,
        fileName: fileTrue.name,
        fileType: fileTrue.type,
        fileSize:fileTrue.size,
        to:to,
        toicon:toicon
    };
    websocket.send(JSON.stringify(data));
    const chatMessages = document.getElementById('chat-messages');
    chatMessages.scrollTop = chatMessages.scrollHeight;
}
function getCurrentTime() {
    const now = new Date();
    return now.getHours().toString().padStart(2, '0') + ':' +
        now.getMinutes().toString().padStart(2, '0');
}

// 发送消息事件
sendBtn.addEventListener('click', sendMessage);
messageInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        sendMessage();
    }
});

$(document).on('click', '.chat-item', function() {
    $(".active-dom").removeClass("active-dom")
    $(this).addClass("active-dom")
    const teacherName = $(this).find('.chat-info h3').text();
    toicon = $(this).find('.avatar img').attr('src');
    // 接收者
    to = teacherName
    console.log(to)
    console.log(toicon)
    if(to == "群聊"){
        $(".chat-title h3").html(to)
        $(".header-left .avatar img").attr("src",toicon)
        $(".chat-title p").html(list.length+"人在线")
    }else{
        $(".chat-title h3").html(to)
        $(".header-left .avatar img").attr("src",toicon)
        $(".chat-title p").html(to+"在线")
    }


    const data = {
        type: "ChangeSingle",
        fromName: fromName,
        // time: new Date().getTime()
        fromicon: myAvatar,
        to: to,
        toicon:toicon
    };
    websocket.send(JSON.stringify(data));
});
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const emojiPicker = document.getElementById('emoji-picker');
    const categoryButtons = document.querySelectorAll('.emoji-categories button');
    const emojiGroups = document.querySelectorAll('.emoji-group');
    const closeBtn = document.querySelector('.close-emoji');

    // 显示/隐藏emoji选择器
    function toggleEmojiPicker(show = true) {
        emojiPicker.style.display = show ? 'block' : 'none';
    }

    // 初始化分类切换
    function initCategorySwitcher() {
        categoryButtons.forEach(button => {
            button.addEventListener('click', function() {
                // 更新激活状态
                categoryButtons.forEach(btn => btn.classList.remove('active'));
                this.classList.add('active');

                // 获取分类名称
                const iconClass = this.querySelector('i').className;
                let category;

                if (iconClass.includes('smile')) category = 'smile';
                else if (iconClass.includes('laugh')) category = 'laugh';
                else if (iconClass.includes('kiss')) category = 'kiss';
                else if (iconClass.includes('surprise')) category = 'surprise';

                // 切换显示对应的表情组
                emojiGroups.forEach(group => {
                    group.style.display = group.dataset.group === category ? 'grid' : 'none';
                });
            });
        });
    }

    // 初始化表情点击事件
    function initEmojiSelection() {
        document.querySelectorAll('.emoji-group button').forEach(btn => {
            btn.addEventListener('click', function() {
                const emoji = this.textContent;
                console.log('选中表情:', emoji);
                // 这里可以添加将表情插入输入框的逻辑
                emojiPicker.style.display='none'
                // 例如: document.getElementById('input-field').value += emoji;
            });
        });
    }


    // 初始化所有功能
    initCategorySwitcher();
    initEmojiSelection();

    // 暴露控制方法到全局
    window.emojiPicker = {
        show: () => toggleEmojiPicker(true),
        hide: () => toggleEmojiPicker(false),
        toggle: () => toggleEmojiPicker(emojiPicker.style.display !== 'block')
    };
});
function setLoading(isLoading) {
    sendBtn.setAttribute('data-loading', isLoading);
    sendBtn.disabled = isLoading; // 禁用按钮
    if (isLoading) {
        sendBtn.innerHTML = " "
    } else {
        sendBtn.innerHTML = '发送';
    }
}